﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using ScrumTime.Models;
using ScrumTime.ViewModels;
using ScrumTime.Helpers;
using ScrumTime.Services;

namespace ScrumTime.Controllers
{
    public class AcceptanceCriteriaController : Controller
    {
        
        ScrumTimeEntities _ScrumTimeEntities;
        StoryService _StoryService;
        AcceptanceCriteriaService _AcceptanceCriteriaService;

        public AcceptanceCriteriaController()
        {
            _ScrumTimeEntities = new ScrumTimeEntities();
            _StoryService = new StoryService(_ScrumTimeEntities);
            _AcceptanceCriteriaService = new AcceptanceCriteriaService(_ScrumTimeEntities);
        }

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult Edit(int id)
        {
            AcceptanceCriteria acceptanceCriteria = _AcceptanceCriteriaService.GetAcceptanceCriteriaById(id);
            return PartialView(acceptanceCriteria);
        }


        // An AJAX driven result that returns just the td's of the read only task...replaces any other
        [Authorize]
        public ActionResult ReadOnly(int id)
        {
            AcceptanceCriteria acceptanceCriteria= _AcceptanceCriteriaService.GetAcceptanceCriteriaById(id);
            return PartialView(acceptanceCriteria);
        }


        // An AJAX driven result that returns just the tbody of the task backlog for the given story
        [Authorize]
        public ActionResult ListById(int storyId)
        {
           TaskCollectionViewModel taskCollectionViewModel = TaskCollectionViewModel.BuildByIdAsc(storyId);            
            return PartialView("List", taskCollectionViewModel);
        }

        private List<UsabilityAffectedAcceptanceCriteria> addAffectedUsabilityFeaturesString(string affectedusabilityFeatures_string)
        {
            List<UsabilityAffectedAcceptanceCriteria> resultado = new List<UsabilityAffectedAcceptanceCriteria>();
            string[] s_ufs = affectedusabilityFeatures_string.Split('-');
            foreach (string s_uf in s_ufs)
            {
                if (s_uf.Length > 0)
                {
                    UsabilityAffectedAcceptanceCriteria af = UsabilityAffectedAcceptanceCriteriaService.GetUsabilityAffectedAcceptanceCriteriaById(_ScrumTimeEntities, int.Parse(s_uf));

                    if (! resultado.Contains(af)) {
                        resultado.Add(af);
                    }
                }
            }
            return resultado;
        }

        private AcceptanceCriteria asignarAffectedUsabilityFeatures(AcceptanceCriteria ac, String ids)
        {
            while (ac.UsabilityAffectedAcceptanceCriterias.Count > 0)
            {
                ac.UsabilityAffectedAcceptanceCriterias.Remove(ac.UsabilityAffectedAcceptanceCriterias.ElementAt(0));
            }
                        
            List<UsabilityAffectedAcceptanceCriteria> lista_uf = addAffectedUsabilityFeaturesString(ids);

            foreach (UsabilityAffectedAcceptanceCriteria uf in lista_uf)
            {
                ac.UsabilityAffectedAcceptanceCriterias.Add(uf);
            }
            return ac;
        }

        // POST: /Task/Save
        [Authorize]
        [HttpPost]
        public ActionResult Save(FormCollection collection)
        {
            try
            {
                string storyId = collection.Get("storyId");
                string id = collection.Get("acceptanceCriteriaId");
                bool newAcceptanceCriteria = false;

                if (id == null || id == "0")
                {
                    id = "0";
                    newAcceptanceCriteria = true;
                }
                string description = collection.Get("description");
                string acceptanceCriteria1 = collection.Get("acceptanceCriteria1");
                string ids_usabilityaffectedAC = collection.Get("usabilityaffectedAC");

                description = UtilServices.ReplaceQuote(description);
                acceptanceCriteria1 = UtilServices.ReplaceQuote(acceptanceCriteria1);


                // TODO:  Validate the story data before saving
                // TODO:  Set the correct product id
                AcceptanceCriteria acceptanceCriteria = new AcceptanceCriteria()
                {
                    AcceptanceCriteriaId = Int32.Parse(id),
                    StoryId = Int32.Parse(storyId),
                    Description = description,
                    AcceptanceCriteria1 = acceptanceCriteria1,
                };
                _AcceptanceCriteriaService.SaveAcceptanceCriteria(acceptanceCriteria);

                AcceptanceCriteria ac = _AcceptanceCriteriaService.GetAcceptanceCriteriaById(acceptanceCriteria.AcceptanceCriteriaId);
                asignarAffectedUsabilityFeatures(ac, ids_usabilityaffectedAC);
                _AcceptanceCriteriaService.SaveAcceptanceCriteria(ac);


                if (newAcceptanceCriteria)
                    return RedirectToAction("ListById", new { storyId = storyId });
                else
                    return RedirectToAction("ReadOnly", new { id = Int32.Parse(id) });
            }
            catch (Exception e)
            {
                return Redirect(ScrumTime.Helpers.ErrorHelper.GetURLGeneralError(e.Message)); 
                //return View();  // TODO:  Handle displaying the exception condition
            }
        }


        //
        // POST: /Task/Delete/5
        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                string storyId = collection.Get("storyId");
                string idAsString = collection.Get("acceptanceCriteriaId");
                _AcceptanceCriteriaService.DeleteAcceptanceCriteria(Int32.Parse(idAsString));
                return RedirectToAction("ListById", new { storyId = storyId });
            }
            catch (Exception e)
            {
                return Redirect(ScrumTime.Helpers.ErrorHelper.GetURLGeneralError(e.Message)); 
                //return View();
            }
        }


        // An AJAX driven result that returns just the td's of the editable "new" task...appends to list
        [Authorize]
        public ActionResult New(int storyId)
        {
            Story story = _StoryService.GetStoryById(storyId);
            AcceptanceCriteria acceptanceCriteria = new AcceptanceCriteria()
            {                
                StoryId = storyId,
                AcceptanceCriteriaId = 0,
                Description = "",
                AcceptanceCriteria1 =""
                
            };
            return PartialView("Edit", acceptanceCriteria);
        }


    }
}
